/**
 * 公交首页
 */
//var showTip, hideTip;
var toFaultSummery, toFaultDetail, examMoreReport, maintPlanMore;
require(['zTreeCheckbox','highcharts','canGrid','highcharts-more','homePageTools'], function () {
	//========================变量
	//TODO
	var lineId,																	//线路id
	//TODO
		lineName,
		dateString = ((new Date()).dateAdd('d',-1)).format(),					//日期字符串
//		dateString = '2016-01-25',												//日期字符串
		dateAr = [],															//日期数组
		dateType = '02',														//日期，默认昨天
		setting,																//线路树配置
		oilConsum=0,															//油耗指标
		oilConsumPer=0,															//油耗环比
		elecConsum=0,															//电耗指标
		elecConsumPer=0,														//电耗环比
		gasConsum=0,															//气耗指标
		gasConsumPer=0,															//气耗环比
		oilCost=0,																//油耗成本
		oilCostPer=0,															//油耗成本环比
		elecCost=0,																//电耗成本
		elecCostPer=0,															//电耗成本环比
		gasCost=0,																//气耗成本
		gasCostPer=0;															//气耗成本环比
	
	//===================函数
	//TODO
	/**
	 * 初始化页面各个元素
	 */
	function initElements(){
		//初始化线路树配置
		setting = {
				view: {
					showIcon: true,
					selectedMulti: false
				},
				data: {
					key: {
						name: "name"
					},
					simpleData: {
						enable: true,
						idKey: "id",
						pIdKey: "parentId",
						rootPId: 0
					}
				},
				callback: {
					beforeClick: function (treeId, treeNode) {
						return treeNode.type == 'LINE';
					},
					onClick: function (event, treeId, treeNode) {
						if (treeNode.id == lineId) {
							return;
						}
						var loadMask = $.createMask();
						setLine(treeNode);
						initPageData();
						setTimeout(function () {
							loadMask.remove();
						}, 50);
					}
				}
		};
		
		//初始化体检报告
		initExamGrid();
		//初始化维保到期表
		maintenanceExpire();
	  
		//初始化能耗排名报表
		initCarEnergyRanking($("#carOilRanking"), 'L/100KM');
		initCarEnergyRanking($("#carElecRanking"), 'KW/100KM');
		initCarEnergyRanking($("#carGasRanking"), 'L/100KM');
		//初始化司机能耗排名
		initDriverEnergyRanking($("#driverOilRanking"), 'L/100KM');
		initDriverEnergyRanking($("#driverElecRanking"), 'KW/100KM');
		initDriverEnergyRanking($("#driverGasRanking"), 'L/100KM');
	    
	}
	
	/**
	 * 初始化体检报告（前五名）
	 */
	function initExamGrid(){
	    $('#examGrid').canGrid({
	        url: '/homeTransit/getLoadExamGrid.htm',
	        colModel: [
	            {name: "carId", label: 'ID', width: '15%', hidden: true},       
	            {name: "licPltNo", label: '车牌', width: '15%'},
	            {name: "examTime", label: '体检日期'},
	            {name: "mftTotal", label: '故障总数', width: '15%', formatter:function(rowIndex, val){
	            	return '<a onClick="examMoreReport()">'+val+'</a>';
	            }},
	            {
	                name: "resolve", label: '未解决', width: '20%',
	                formatter: function (rowIndex, val,rowData) {
	                	var total = val;
	                	if(total >= 100){
	                		total = '99+';
	                		return '<a onClick="examMoreReport(\'' + rowData.carId + '\')"><span class="num" onMouseOver="showTips(this,\''+val+'\')" onMouseOut="hideTips(this)">{0}</span></a>'.format(total);
	                	}else{
	                		return '<a onClick="examMoreReport(\'' + rowData.carId + '\')"><span class="num">{0}</span></a>'.format(total);
	                	}
	                }
	            }
	        ]
	    });
	}
	
	/**
	 * 初始化维保到期表
	 */
	function maintenanceExpire(){
	    $('#todoGrid').canGrid({
	        url: '/homeTransit/getLoadMaintenanceEvent.htm',
	        colModel: [
	            {name: "licPltNo", label: '车牌号', width: '15%',
	            	formatter:function(rowIndex, val){
	            		return "<a onClick='maintPlanMore()'>"+ val + "</a>";
	            	}},
	            {name: "totalMile", label: '运行里程', width: '20%',
	            	formatter:function(rowIndex, val){
	            		if(!val)
	            			val = 0;
	            		return "<a onClick='maintPlanMore()'>"+ val + "</a>";
		           	}},
	            {name: "lastMaintenMile", label: '上次维保里程', width: '20%',
		           	formatter:function(rowIndex, val){
		           		if(!val)
	            			val = 0;
		           		return "<a onClick='maintPlanMore()'>"+ val + "</a>";
		            }},
	            {name: "itrvMile", label: '计划保养里程', width: '20%',
		            formatter:function(rowIndex, val){
		            	if(!val)
	            			val = 0;
		            	return "<a onClick='maintPlanMore()'>"+ val + "</a>";
		            }},
	            {
	                name: "remaindMile", label: '剩余里程',
	                formatter: function (rowIndex, val, rowData) {
	                	if(!val)
	            			val = 0;
	                    var html = '<span class="date-limit"><i style="{0}"></i></span><span style="color: red;">{1}</span></td>';
	                    var width = '';
	                    var text = val;
	                    if (val != null) {
	                        text += 'km';
	                        width = 'width:{0}%'.format((val / rowData.RANK_VAL4) * 100);
	                    }
	                    html = '<a onClick="maintPlanMore()">' + html + '</a>';
	                    return html.format(width, text);
	                }
	            }
	        ]
	    });
	}
	
	/**
	 * 初始车辆能耗排名
	 */
	function initCarEnergyRanking(obj, unit){
		obj.canGrid({
			url: "/homeTransit/getEnergyCarsRanking.htm",
			height:200,
	        colModel: [
	            {name: "rankSn", label: '排名', align:'center',width: '15%'},
	            {name: "lineName", label: '线路', align:'center',width: '22%'},
	            {name: "licPltNo", label: '车牌号', align:'center',width: '22%'},
	            {name: "energyConsMile", align:'center',label: '百公里能耗('+unit+')'}
	        ]
	    });
	}
	/**
	 * 初始司机能耗排名
	 */
	function initDriverEnergyRanking(obj, unit){
		obj.canGrid({
			url: "/homeTransit/getEnergyStatusRanking.htm",
			height:200,
	        colModel: [
	            {name: "rankSn", label: '排名', align:'center',width: '10%'},
	            {name: "lineName", label: '线路', align:'center',width: '17%'},
	            {name: "licPltNo", label: '车牌号', align:'center',width: '17%'},
	            {name: "drvName", label: '驾驶员', align:'center',width: '17%'},
	            {name: "energyConsMile", align:'center',label: '百公里能耗('+unit+')'}
	        ]
	    });
	}
	
	/**
     * 设置当前线路名称及ID
     * @param item ztree节点
     */
    function setLine(item) {
        lineId = item.id;
        $("#showlineName").html("当前线路 : " + item.name);
        lineName = item.name;
    }
  
    /**
     * 生成线路树
     */
    function initLineTree(){
		$.ajaxExt({
			async : false,
	        url: "/baseOrgan/getLeftOrg4Line.htm"
	    }).done(function(result){
	    	if ($.isArray(result)) {
                $.each(result, function (index, item) {
                    if (item.type == 'LINE') {
                        setLine(item);
                        return false;
                    }
                });
                $("#lineTree").createTree(setting, result, {search: $('#lineSelected')}).expandAll(true);
            }
	    });
	}
	
    /**
     * 获取日期类型对应日期数据
     */
    function getFullDate(){
    	//TODO
    	$.ajaxExt({
    		async : false,
    		url:"/homeTransit/getFullDate.htm",
    		data:{
    			"dateType":dateType,
    			"yesterday":((new Date()).dateAdd('d',-1)).format()
//    			"yesterday":'2016-01-25'
    		}
    	}).done(function(data){
    		if(data && data.length > 0){
    			for(var i =0;i<data.length;i++){
    				dateAr.push(data[i].trendDate);
    			}
    			if(dateType=='02'){
    				//TODO
    	    		dateString = ((new Date()).dateAdd('d',-1)).format();
//    	    		dateString = '2016-01-25';
    	    	}else if(dateType == '03'){
    				dateString = data[0].trendDate+"-"+data[data.length-1].trendDate;
    			}else if(dateType == '04' || dateType == '05'){
    				dateString = data[0].trendDate.substring(0, 7)+"月";
    			}else if(dateType == '07' || dateType == '06'){
    				dateString = data[0].trendDate.substring(0, 4)+"年";
    			}
    		}
    	});
    }
    
    /**
     * 格式化趋势图横坐标日期
     */
    // function xAxisDateFormat(categories, tmpDate){
    // 	if(dateType== '02' || dateType== '03'){
    // 		categories.push(tmpDate.substring(5));
    // 	}else if(dateType== '04' || dateType== '05'){
    // 		categories.push(tmpDate.substring(8)+"日");
    // 	}else if(dateType== '06' || dateType== '07'){
    // 		categories.push(tmpDate.substring(5)+"月");
    // 	}
    // }
    
	/**
	 * 生成概况图
	 */
	function initOverviewChart(tmpDateString){
		$.ajaxExt({
			url:"/homeTransit/getOverviewChart.htm",
			data:{
				"dateType":dateType,
				"lineId":lineId,
				"funcType":"getOverviewChart",
				"className":"OverviewChartVo"
			}
		}).done(function(data){
				var series = [{name: '能力水平得分', data: [0,0,0,0,0], pointPlacement: 'on'}];
				if(data && data.length>0 && data[0].safetyVal){
					series[0].data[0] = data[0].safetyVal ? data[0].safetyVal : 0;
					series[0].data[1] = data[0].behaviousVal ? data[0].behaviousVal : 0;
					series[0].data[2] = data[0].energyVal ? data[0].energyVal : 0;
					series[0].data[3] = data[0].maintenanceVal ? data[0].maintenanceVal : 0;
					series[0].data[4] = data[0].inmotionVal ? data[0].inmotionVal : 0;
				}
				$("#totalStatus").highcharts({ 
					chart: { polar: true, type: 'line' }, 
					title: { text: '综合能力水平' }, 
					subtitle: { 
						text: lineName+' '+tmpDateString+'综合能力'
					},
					credits: {
                        enabled: false
                    },
					pane: { size: '80%' }, 
					xAxis: { 
						categories: ['车辆安全', '驾驶行为', '能耗水平', '机务管理','营运能力'],
						tickmarkPlacement: 'on', 
						lineWidth: 0,
						gridLineWidth: 1
					}, 
					yAxis: { 
						minorTickInterval: 'auto',
						gridLineInterpolation: 'polygon', 
						lineWidth: 0,
						max: 100,
						min: 0
					}, 
					tooltip: { shared: true, 
						pointFormat: '<span style="color:{series.color}">{series.name}: <b>{point.y:,.0f}</b><br/>' 
					}, 
					legend: { align: 'center', 
			            verticalAlign: 'bottom',  
			            layout: 'vertical' }, 
					series: series
				});
		});
	}
	
	/**
	 * 加载指标
	 */
	function initTotallyStatus(){
		$.ajaxExt({
			url:"/homeTransit/getInitTotallyStatus.htm",
			data:{"dateType":dateType,"lineId":lineId,"funcType":"initTotallyStatus","className":"TotallyStatusVo"}
		}).done(function(data){
			if(data && data.length>0 && data[0].totalCars){
				$("#totalCars").html(data[0].totalCars+"<i>辆</i>");
				$("#motionCars").html(data[0].motionCars+"<i>辆</i>");
				$("#driveMiles").html(data[0].totalMiles+"<i>KM</i>");
				$("#avgOilConsum").html(data[0].avgOilConsum+"<i>L</i>");
				$("#avgElecConsum").html(data[0].avgElecConsum+"<i>KWH</i>");
				$("#avgGasConsum").html(data[0].avgGasConsum+"<i>L</i>");
				$("#mostSeriousFaultsCount").html(data[0].seriousFaultCounts+"<i>次</i>");
				$("#mostSeriousCarsCount").html(data[0].seriousFaultCars+"<i>辆</i>");
			}else{
				$("#totalCars").html("0<i>辆</i>");
				$("#motionCars").html("0<i>辆</i>");
				$("#driveMiles").html("0<i>KM</i>");
				$("#avgOilConsum").html("0<i>L</i>");
				$("#avgElecConsum").html("0<i>KWH</i>");
				$("#avgGasConsum").html("0<i>L</i>");
				$("#mostSeriousFaultsCount").html("0<i>次</i>");
				$("#mostSeriousCarsCount").html("0<i>辆</i>");
			}
		});
	}
	
	/**
	 * 代办事项
	 */
	function loadSchedule(){
		
		if(lineId && lineId != ''){
			
			$.ajaxExt({
				url:"/homeTransit/getLoadSchedule.htm",
				data:{"dateType":dateType,"lineId":lineId,"funcType":"loadSchedule","className":"ScheduleVo"}
			}).done(function(data){
				if(data && data.length >0){
					$("#FAULT_COUNT").html("<h4>"+data[0].faultCount+"</h4><p>车辆故障</p><span class='icon'></span>");
					$("#BHV_COUNT").html("<h4>"+data[0].bhvCount+"</h4><p>行为异常</p><span class='icon'></span>");
					$("#ENER_EXCPT_VAL").html("<h4>"+data[0].enerExcptVal+"</h4><p>超速次数</p><span class='icon'></span>");
					$("#MAINT_EXPIRE").html("<h4>"+data[0].maintExpire+"</h4><p>维保过期</p><span class='icon'></span>");
				}else{
					$("#FAULT_COUNT").html("<h4>0</h4><p>车辆故障</p><span class='icon'></span>");
					$("#BHV_COUNT").html("<h4>0</h4><p>行为异常</p><span class='icon'></span>");
					$("#ENER_EXCPT_VAL").html("<h4>0</h4><p>超速次数</p><span class='icon'></span>");
					$("#MAINT_EXPIRE").html("<h4>0</h4><p>维保过期</p><span class='icon'></span>");
				}
			});
		}
		
	}
	
	/**
	 * 初始化安全指标
	 */
	function initSafeIndex(){
		$.ajaxExt({
			url:"/homeTransit/getSafetyIndexStatus.htm",
			data:{"dateType":dateType,"lineId":lineId,"funcType":"safetyIndexStatus","className":"HomeSafetyIndexVo"}
		}).done(function(data){
			if(data && data.length>0 && data){
				$("#seriousFaults").html((data[0].seriousFaults ? data[0].seriousFaults : 0));
				fillPerVal($("#seriousFaultsPer"), (data[0].avgSerious ? data[0].avgSerious : 0));
				$("#commonFaults").html((data[0].commonFaults ? data[0].commonFaults : 0));
				fillPerVal($("#commonFaultsPer"), (data[0].avgCommon ? data[0].avgCommon : 0));
				$("#FaultCars").html((data[0].faultCars ? data[0].faultCars : 0));
				fillPerVal($("#FaultCarsPer"), (data[0].avgFaultCars ? data[0].avgFaultCars : 0));
				$("#unsafeBhvs").html((data[0].ubsafeBhv ? data[0].ubsafeBhv : 0));
				fillPerVal($("#unsafeBhvsPer"), (data[0].avgUbsafeBhv ? data[0].avgUbsafeBhv : 0));
				$("#unsafeBhvDrvs").html((data[0].ubsafeCars ? data[0].ubsafeCars : 0));
				fillPerVal($("#unsafeBhvDrvsPer"), (data[0].avgUbsafeCars ? data[0].avgUbsafeCars : 0));
			}else{
				$("#seriousFaults").html("0");
				fillPerVal($("#seriousFaultsPer"), 0);
				$("#commonFaults").html("0");
				fillPerVal($("#commonFaultsPer"), 0);
				$("#FaultCars").html("0");
				fillPerVal($("#FaultCarsPer"), 0);
				$("#unsafeBhvs").html("0");
				fillPerVal($("#unsafeBhvsPer"), 0);
				$("#unsafeBhvDrvs").html("0");
				fillPerVal($("#unsafeBhvDrvsPer"), 0);
			}
		});
	}
	
	/**
	 * 填充环比
	 * @param obj 页面同比元素
	 * @param val 环比值
	 */
	function fillPerVal(obj, val){
		obj.removeClass();
		if(isNaN(parseFloat(val)) || val == 0){
			val = "0.0";
		}
		obj.addClass("icon-arrow-up");
		obj.html(val+"%");
		if(val < 0){
			obj.addClass("icon-arrow-down");
		}else if(val == 0){
			obj.addClass("icon-arrow-unchanged");
		}
	}
	
	/**
	 * 生成安全趋势图
	 * @param idxType 业务类型
	 * @param obj 页面图表元素
	 * @param text 标题
	 */
	function initSafetyTendencyChart(idxType, obj){
		$.ajaxExt({
			url:"/homeTransit/getInitSafetyTendencyChart.htm",
			data:{"dateType":dateType,"lineId":lineId,"funcType":"initSafetyTendencyChart","idxType":idxType,"className":"SafetyTendencyVo"}
		}).done(function(data){
			var category = [], series = [];
            var mainTitle = '',
            	subTitle = '线路：'+lineName+' 时间：'+dateString;
            //格式化数据
            formatSafetyTendencyData(data, dateType, category, series, dateAr);
            //生成趋势图
            createMultiTendencyChart(obj, mainTitle, subTitle, category, null, '次', series, dateType);
		});
	}
	
	/**
	 * 初始化能耗指标
	 */
	function initEnergyIndex(){
		$.ajaxExt({
			url:"/homeTransit/getInitEnergyIndex.htm",
			data:{"dateType":dateType,"lineId":lineId,"funcType":"initEnergyIndex","className":"EnergyIndexVo"}
		}).done(function(data){
//			console.info(data[0].a);
//			if(data[0].a != null ){
//				console.info(data[0].oilConsum);
//			}
			if(data && data.length>=1 && data){
				//三种能耗指标
				oilConsum = data[0].oilConsum ? data[0].oilConsum : 0;
				oilConsumPer = data[0].oilPer ? data[0].oilPer : 0;
				elecConsum = data[0].elecConsum ? data[0].elecConsum : 0;
				elecConsumPer = data[0].elecPer ? data[0].elecPer : 0;
				gasConsum = data[0].gasConsum ? data[0].gasConsum : 0;
				gasConsumPer = data[0].gasPer ? data[0].gasPer : 0;
				$("#avgEnergyIndex").html(oilConsum);
				fillPerVal($("#avgEnergyIndexPer"), oilConsumPer);
				//三种能耗成本
				oilCost = data[0].oilCostVal ? data[0].oilCostVal : 0;
				oilCostPer = data[0].oilCostPer ? data[0].oilCostPer : 0;
				elecCost = data[0].elecCostVal ? data[0].elecCostVal : 0;
				elecCostPer = data[0].elecCostPer ? data[0].elecCostPer : 0;
				gasCost = data[0].gasCostVal ? data[0].gasCostVal : 0;
				gasCostPer = data[0].gasCostPer ? data[0].gasCostPer : 0;	
				$("#avgEnergyCost").html(oilCost);
				fillPerVal($("#avgEnergyCostPer"), oilCostPer);
				//运行里程和运行时长
				$("#energyException").html((data[0].enerExcptVal ? data[0].enerExcptVal : 0));
				fillPerVal($("#energyExceptionPer"), (data[0].enerExcptPer ? data[0].enerExcptPer : 0));
				$("#energyExceptionCars").html((data[0].enerCarsVal ? data[0].enerCarsVal : 0));
				fillPerVal($("#energyExceptionCarsPer"), (data[0].enerCarsPer ? data[0].enerCarsPer : 0));
			}else{
				$("#avgEnergyIndex").html("0");
				fillPerVal($("#avgEnergyIndexPer"), 0);
				$("#avgEnergyCost").html("0");
				fillPerVal($("#avgEnergyCostPer"), 0);
				$("#energyException").html("0");
				fillPerVal($("#energyExceptionPer"), 0);
				$("#energyExceptionCars").html("0");
				fillPerVal($("#energyExceptionCarsPer"), 0);
			}
		});
	}
	
	/**
	 * 初始化能耗影响因素
	 */
	function loadInfluence(){
		$.ajaxExt({
			url:"/homeTransit/getEnergyInfluence.htm",
			data:{"funcType":"energyInfluence", "dateType":dateType, "lineId":lineId,"className":"EnergyInfluenceVo"}
		}).done(function(data){
			var html = "";
			if(data && data.length > 0){
				for(var i=0; i<data.length; i++){
					html += '<li>'+data[i].influence+'</li>';
					if(i==2){
						$("#energyDriversFactors").html(html);
						html = '';
					}
				}
			}
			$("#energyCarsFactors").html(html);
		});
	}
	
	/**
	 * 变更隐藏/显示
	 * @param type 显示标记 (0:表示第一个元素隐藏，第二个元素显示,1:反之)
	 * @param obj1 设置显示/隐藏的第一个元素
	 * @param obj2 设置显示/隐藏的第二个元素
	 */
	function showHideToggle(type, obj1, obj2){
		if(type==0){
			obj1.hide();
			obj2.show();
		}else{
			obj2.hide();
			obj1.show();
		}
	}
	
	/**
	 * 生成趋势图(油，电，气) 010701 010702 010703
	 * @param obj 图形元素
	 * @param type 图形类型
	 * @param idxType 业务类型
	 * @param title 标题
	 * @param unit 单位
	 * @param color 颜色
	 */
	function initTendencyChart(obj, type, idxType,  title, unit, color){
		obj.html("");
		$.ajaxExt({
			url:"/homeTransit/getEnergyTendencyChart.htm",
			data:{"funcType":"energyTendencyChart", "dateType":dateType, "lineId":lineId, "idxType":idxType,"className":"EnergyTendencyVo"}
		}).done(function(data){
			var category = [],
				series = [{name:"百公里"+title+"耗", data:[]}],
				mainTitle = '百公里'+title+'耗趋势',
				subTitle = '线路：'+lineName+' 时间：'+dateString;
				if(!lineName || lineName == undefined){
					subTitle = '线路：- 时间：'+dateString;
				}
			//数据格式
			formatEnergyTendencyData(data, dateType, category, series, dateAr);
			//趋势图
			createEnergyTendencyChart(obj, type, color, mainTitle, subTitle, category, unit, series, dateType, idxType, data);
		});
	}	 
	
	/**
	 * 加载能耗趋势图
	 */
	var loadEnergyTendency = function(){
		initTendencyChart($("#oilTendencyChart"), "areaspline", "010701",  "油", "L", '#FF5151');
		initTendencyChart($("#elecTendencyChart"), "areaspline", "010702",  "电", "KWH", '#79FF79');
		initTendencyChart($("#gasTendencyChart"), "areaspline", "010703",  "气", "L", '#FF9224');
	};
	
	/**
	 * 加载车辆能耗排名报表，司机能耗排名报表
	 */
	var loadEnergyRankingTab = function(){
		$("#carOilRanking").canGrid('reload', {params:{"funcType":"energyCarsRanking" , "dateType":dateType,"lineId":lineId, "idxType":"010901", "className":"EnergyRankingVo"}});
		$("#carElecRanking").canGrid('reload', {params:{"funcType":"energyCarsRanking" , "dateType":dateType,"lineId":lineId, "idxType":"011001", "className":"EnergyRankingVo"}});
		$("#carGasRanking").canGrid('reload', {params:{"funcType":"energyCarsRanking" , "dateType":dateType,"lineId":lineId, "idxType":"011101", "className":"EnergyRankingVo"}});
		$("#driverOilRanking").canGrid('reload', {params:{"funcType":"energyStatusRanking" , "dateType":dateType,"lineId":lineId, "idxType":"010902", "className":"EnergyRankingVo"}});
		$("#driverElecRanking").canGrid('reload', {params:{"funcType":"energyStatusRanking" , "dateType":dateType,"lineId":lineId, "idxType":"011002", "className":"EnergyRankingVo"}});
		$("#driverGasRanking").canGrid('reload', {params:{"funcType":"energyStatusRanking" , "dateType":dateType,"lineId":lineId, "idxType":"011102", "className":"EnergyRankingVo"}});
	};
	
	/**
	 * 加载体检报告
	 */
	function loadExamReport(){
		$("#examGrid").canGrid('reload', {params:{"funcType":"loadExamGrid", "dateType":dateType, "lineId":lineId, "className":"MaintExamGridVo"}});
	}
	
	//TODO
	/**
	 * 加载机务问题
	 */
	function loadMaintenanceMatter(){
		$.ajaxExt({
			url:"/homeTransit/getLoadMaintenanceData.htm",
			data:{"funcType":"loadMaintenanceData", "dateType":dateType, "lineId":lineId, "idxType":"011201", "className":"MaintenanceFaultVo"}
		}).done(function(data){
			var html = "";
			if(data && data.length > 0){
				for(var i=0;i<data.length;i++){
					var total = data[i].maintFaultItem;
					if(total >= 100){
						total = '99+';
						html += '<li><a onClick="toFaultDetail(\''+data[i].mftId+'\', \''+data[i].maintFaultCount+'\')"><i  onMouseOver="showTips(this, \''+data[i].maintFaultItem+'\')" onMouseOut="hideTips(this)">'
						+total+'</i><em>'+(i+1)+'</em><span>'+data[i].maintFaultCount+'</span></a></li>';
					}else{
						html += '<li><a onClick="toFaultDetail(\''+data[i].mftId+'\', \''+data[i].maintFaultCount+'\')"><i>'+total+'</i><em>'+(i+1)+'</em><span>'+data[i].maintFaultCount+'</span></a></li>';
					}
				}
			}
			$("#maintenanceMatter").html(html);
		});
	}
	
	
	toFaultDetail = function(mftTypeCode, mftTypeName){
		var data = {};
		//data.statisType = 'LINE';
		data.lineId = lineId;
		data.dateType = dateType;
		if(!mftTypeCode)
			mftTypeCode = "";
		data.mftTypeCode = mftTypeCode;
		data.mftTypeName = mftTypeName;
		$.openTab('c60acb21701a4b63ba3e6d9ddd502ab0', 'searchFaultDetail', [data]);
	}
	
	/**
	 * 加载维保代办事件
	 */
	function loadMaintenanceEvent(){
		$("#todoGrid").canGrid('reload', {params:{"funcType":"getMaintenEventList", "dateType":dateType, "lineId":lineId, "className":"MaintenanceExpireVo"}});
	}
	
	/**
	 * 更改能耗标题和能耗成本指标
	 */
	function changeIndexTitleAndCost(type, costVal, perVal, unit){
		$("#energyIndexTitle").html('平均百公里'+type+'耗'+unit);
		$("#costIndexTtile").html('平均百公里'+type+'耗费用(元)');
		$("#avgEnergyCost").html(costVal);
		fillPerVal($("#avgEnergyCostPer"), perVal);
	}
	
	/**
	 * 加载页面各个功能
	 */
	function initPageData(){
		persistCurrentCondition(lineId, lineName, dateType);
		
		$("#changeOilIndex").addActiveClass();
		initOverviewChart(dateString);
		initTotallyStatus();
		loadSchedule();
		initSafeIndex();
		$('#faultsTendencyChart').empty();
		initSafetyTendencyChart("010501", $('#faultsTendencyChart'), '故障趋势');
		$('#unsafeBhvTendencyChart').empty();
		initSafetyTendencyChart("010601", $('#unsafeBhvTendencyChart'), '不安全行为趋势');
		initEnergyIndex();
		loadInfluence();
		loadEnergyTendency();
		loadEnergyRankingTab();
		loadExamReport();
		loadMaintenanceMatter();
		loadMaintenanceEvent();
	}
	
	/**
	 * 自动加载
	 */
	function autoLoadData(){
		var condition = getCurrentCondition();
		var _cookileLineId;
		if(condition[0]){
			_cookileLineId = condition[0];
		}
		if (condition[1]) {
			dateType = condition[1];
		}
		if(lineId){
			var treeObj = $.fn.zTree.getZTreeObj("lineTree");
			var node = treeObj.getNodeByParam("id", _cookileLineId, null);
			if (node) {
				$("#dateDiv").find('a').removeClass("active");
				$("#dateDiv").find('a[val="' + dateType + '"]').addClass("active");
				lineId = _cookileLineId;
				lineName = node.name;
				$("#showlineName").html("当前线路 : " + lineName);
				treeObj.selectNode(node);
				getFullDate();
				initPageData();
			} else {
				//载入后默认加载昨天
				$("#dateDiv").find('a:first').click();
			}
		}else{
			//载入后默认加载昨天
			$("#dateDiv").find('a:first').click();
		}
	}
	
	//TODO
	/**
	 * 显示tip
	 */
	var showTips = function(obj, val) {
		$(obj).html(val);
	}
	
	/**
	 * 隐藏tip
	 */
	var hideTips = function(obj) {
		$(obj).html("99+");
	} 
	
	
	//----------------------------------跳转函数
	/**
	 * 跳转到故障统计
	 */
	toFaultSummery = function(sign, mftTypeCode){
		var data = {};
		data.statisType = 'LINE';
		data.lineId = lineId;
		data.dateType = dateType;
		data.mftGradeCode = sign;
		if(!mftTypeCode)
			mftTypeCode = "";
		data.mftTypeCode = mftTypeCode;
		
		$.openTab('4270f3bb02fa4bf0bab5f40a351ae747', 'searchFaultSummery', [data]);
	}
	
	/**
	 * 跳转对应功能明细页
	 */
	function itemSearch(id){
		var data = {};
		data.today = (new Date()).format();
		data.lineId = lineId;
		$.openTab(id, 'itemSearch', [data]);
	}
	
	/**
	 * 跳转不安全行为统计
	 */
	function toUnsafeSummery(statisType){
		var data = {};
//		data.statisType = 'LINE';
		data.statisType = statisType;
		data.lineId = lineId;
		data.dateType = dateType;
		//data.mftTypeCode = mftTypeCode;
		if(statisType==='DRIVER'){
			$.openTab('0faa7a5b3279477b813cefe5a5362bd1', 'searchUnsafeSummery', [data]);
		}
		else if(statisType==='LINE'){
			$.openTab('0faa7a5b3279477b813cefe5a5362bd2', 'searchUnsafeSummery', [data]);
		}
	}
	
	/**
	 * 跳转到能耗明细
	 */
	function energyDetail(id, energyType){
		var data = {};
		var fuelTypeCode = [];
		if($("#changeOilIndex").attr("class") == 'active'){
			fuelTypeCode = ['1', '2'];
		}else if($("#changeElecIndex").attr("class") == 'active'){
			fuelTypeCode.push('3');
		}else if($("#changeGasIndex").attr("class") == 'active'){
			fuelTypeCode = ['4', '5'];
		}
		data.energyType = fuelTypeCode;
		if(energyType){
			data.energyType = energyType;
		}
		data.energyTimeType = '10';
		if(dateType == '06' || dateType == '07'){
			data.energyTimeType = '7';
		}
		data.lineId = lineId;
		data.dateType = dateType;
		$.openTab(id, 'searchEnergyDetail', [data]);
	}
	
	examMoreReport = function(carId){
		$.openTab('f8db8e980e614b0eb26e7f7d0c1de402','itemSearch',[carId]);
	}
	
	maintPlanMore = function(){
		var data = {};
		data.lineId = lineId;
		$.openTab('7c3f52086ec347649fba50b59a84494b', 'itemSearch', [data]);
	}
	
	//=========================事件
	//TODO
	//日期按钮设置1
	$("#dateDiv").find('a').click(function(){
		$("#dateDiv").find('a').removeClass("active");
		dateType = $(this).attr("val");
		dateAr = [];
		getFullDate();
		//加载页面各项
		$(this).addClass("active");
		initPageData();
	});
	
	//变更百公里能耗
	$("#changeOilIndex").click(function(){
		$(this).addActiveClass();
		$("#avgEnergyIndex").html(oilConsum);
		fillPerVal($("#avgEnergyIndexPer"), oilConsumPer);
		changeIndexTitleAndCost('油', oilCost, oilCostPer, "<i>（L）</i>");
	});
	$("#changeGasIndex").click(function(){
		$(this).addActiveClass();
		$("#avgEnergyIndex").html(gasConsum);
		fillPerVal($("#avgEnergyIndexPer"), gasConsumPer);
		changeIndexTitleAndCost('气', gasCost, gasCostPer, "<i>（L）</i>");
	});
	$("#changeElecIndex").click(function(){
		$(this).addActiveClass();
		$("#avgEnergyIndex").html(elecConsum);
		fillPerVal($("#avgEnergyIndexPer"), elecConsumPer);
		changeIndexTitleAndCost('电', elecCost, elecCostPer, "<i>（KWH）</i>");
	});
	
	////设置隐藏显示切换
	$("input[name='changeOilRanking']").click(function(){
		var sign = $("input[name='changeOilRanking']:checked").val();
		showHideToggle(sign, $("#driverOilRankingDiv"), $("#carOilRankingDiv"));
	});
	$("input[name='changeElecRanking']").click(function(){
		var sign = $("input[name='changeElecRanking']:checked").val();
		showHideToggle(sign, $("#driverElecRankingDiv"), $("#carElecRankingDiv"));
	});
	$("input[name='changeGasRanking']").click(function(){
		var sign = $("input[name='changeGasRanking']:checked").val();
		showHideToggle(sign, $("#driverGasRankingDiv"), $("#carGasRankingDiv"));
	});
	
	//TODO
	//------------------------------跳转部分
	//各跳转链接
	//	事项跳转
	$("#itemFaultDetail").click(function(){
		itemSearch('c60acb21701a4b63ba3e6d9ddd502ab0');
	});
	$("#itemBhvDetail").click(function(){
		itemSearch('9e9e90184a644a069ece59eca8cae9fe');
	});
	$("#itemOverspeed").click(function(){
		itemSearch('82574146a7d34a1bb4423bafbeddbe21');
	});
	$("#itemMaintExpr").click(function(){
		itemSearch('7c3f52086ec347649fba50b59a84494b');
	});
	//	跳转故障
	$("#seriousFault").click(function(){
		toFaultSummery('MFTC0002');
	});
	$("#normalFault").click(function(){
		toFaultSummery('MFTC0001');
	});
	$("#faultVehicles, #faultsChartMore").click(function(){
		toFaultSummery('');
	});
	//	不安全行为
	$("#unsafeBhvMore, #unsafeChartMore").click(function(){
		toUnsafeSummery('LINE');
	});
	
	$("#unsafeBhvDrvsMore").click(function(){
		toUnsafeSummery('DRIVER');
	});
	
	// 能耗明细
	$("#avgEnergyIndexMore, #avgEnergyCostMore, #energyMileMore, #energyDurationMore").click(function(){
		energyDetail('d0c6f14c2d3047fb91ec4c6e6bd55590');
	});
	
	$("#oilRankMore").click(function(){
		var sign = $("input[name='changeOilRanking']:checked").val();
		var id = getFuncId(sign);
		energyDetail(id, ['1', '2']);
	});
	$("#elecRankMore").click(function(){
		var sign = $("input[name='changeElecRanking']:checked").val();
		var id = getFuncId(sign);
		energyDetail(id, ['3']);
	});
	$("#gasRankMore").click(function(){
		var sign = $("input[name='changeGasRanking']:checked").val();
		var id = getFuncId(sign);
		energyDetail(id, ['4', '5']);
	});
	
	function getFuncId(sign){
		var id = 'd280237883a94d72a90530e4ace3931d';
		if(sign == '1'){
			id = '22a8cf4a8bef40ca9231911bce49d01b';
		}
		return id;
	}
	
	
	//初始化页面各个元素
	initElements();
	//初始化页面
	initLineTree();
	//加载
	autoLoadData();
	
	
	
});